package auth

import (
	"errors"
	"fmt"
	"time"

	"gitee.com/les49/esgo/utils/econv"

	"github.com/golang-jwt/jwt/v4"
)

var (
	JwtErrExpiredToken = errors.New("token is expired")
	JwtRrrInvalidToken = errors.New("token is invalid")
)

func NewJwtToken(secretKey string, expSeconds int64, data map[string]interface{}) (string, error) {
	iat := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + expSeconds
	claims["iat"] = iat

	for k, v := range data {
		claims[k] = v
	}

	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	jwtstr, err := token.SignedString([]byte(secretKey))
	if err != nil {
		return "", errors.New("jwt signed error")
	}

	return jwtstr, nil
}

func ParseJwtToken(secretKey string, tokenString string) (map[string]interface{}, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secretKey), nil
	})

	if err != nil {
		return nil, JwtRrrInvalidToken
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		exp := econv.Int64(claims["exp"])
		if exp <= 0 {
			return nil, JwtRrrInvalidToken
		}

		if exp < time.Now().Unix() {
			return nil, JwtErrExpiredToken
		}

		return claims, nil
	}

	return nil, JwtRrrInvalidToken
}
